<?php
namespace Admin\Controller;
use Lib\Controller\AdminBaseController;
require_once __ROOT__ . '/vendor/riverslei/payment-4.0/autoload.php';

use Payment\Common\PayException;
use Payment\Client\Refund;
use Payment\Client\Query;
use Payment\Config;
use Payment\Common\WxConfig;

class OrdersController extends AdminBaseController{

    private $ordersModel;
    private $refundModel;
    private $serverModel;
    private $washLogModel;

    public function __construct(){
        $this->ordersModel = D('Order');
        $this->refundModel = D('Refund');
        $this->serverModel = D('server');
        $this->washLogModel = D('washLog');
        parent::__construct();
    }

    /**
     * 订单列表
     */
    public function orders_list() {
        $where = null;
        if (IS_POST) {
            switch(I('post.order_find')){
                case 0 :
                    $condition = 'ordersn';
                    break;
                case 1 :
                    $condition = 'phone';
                default:
                    break;
            }
            $orderNo = I('post.keywords',null,'string');
            if($condition=='ordersn'){
                if (trim($orderNo) != null) {
                    $where['o.ordersn'] = array('like','%'.$orderNo.'%');
                }
            }
            else if($condition=='phone'){
                $where['u.phone'] = array('like','%'.$orderNo.'%');
            }

            switch (I('post.search')){
                case 0 :
                    $where['o.status'] = 0;
                    break;
                case 1 :
                    $where['o.status'] = 1;
                    break;
                case -1 :
                    $where['o.status'] = -1;
                    break;
                case -2 :
                    $where['o.status'] = -2;
                    break;
                case -3 :
                    $where['o.status'] = -3;
                    break;
                case -4 :
                    $where['o.status'] = -4;
                    break;
                case 99 :
                    $where['o.status'] = array('gt','-99');
                    break;
                default:
                    break;
            }

        }
        if(session(C('USER_AUTH_KEY')) != -1){
            $where['o.server_id'] = session(C('USER_AUTH_KEY'));
        }

        //获取订单数量
        $ordersNum = $this->ordersModel->getOrdersCount($where);
        //分页
        $p     = I('get.p',1);
        $page  = new \Lib\ORG\Page($ordersNum);
        $limit = $page->listRows;
        $pageString  = $p.','. $limit;
        $orderList = $this->ordersModel->getOrderList($page,$where,$pageString);

        foreach($orderList as $key =>$val){
            if(isset($val['coupon_id'])){
                //獲取優惠券信息
                $couponPrice = D('coupon')->where('id = '.$val['coupon_id'])->find();
                if ($val['price']-$couponPrice['price']>0 && $val['price']-$couponPrice['price'] < 0.01) {
                    $amount = 0.01;
                }else if($val['price']-$couponPrice['price'] <0 ){
                    $amount = 0;
                }else{
                    $amount = $val['price'] - $couponPrice['price'];
                }
                $orderList[$key]['real_price']      = sprintf("%.2f",$amount);
                $orderList[$key]['coupon_name']     = $val['name'];
                $orderList[$key]['coupon_price']    = $val['price'];
            }

            $serverWhere['server_address_id']        = $val['server_address_id'];
            $orderList[$key]['server_address_staff'] = $this->serverModel->where($serverWhere)->select();
            // $orderList[$key]['server_address_staff'] = $this->serverModel->where('server_address_id = '.$val['server_address_id'])->select();  // 林业程写的
        }

        //输出
        if ($orderList) {
            $this->assign('orderList', $orderList );
        }
        $this->assign('page', $page->show());
        $this->display();
    }

    /**
     * 查看订单详情
     */
    public function order_details(){
        if (IS_GET) {
            $where['o.id'] = I('get.id',0,'int');
            if ($where['o.id'] <= 0) {
                //订单ID错误
                $this->redirect(MODULE_NAME.'/'.CONTROLLER_NAME.'/orders_list');
            }

            $orderInfo =  $this->ordersModel->getOrderList($page='',$where,$p=null,$type="find");
            if(isset($orderInfo['coupon_id'])){
                //獲取優惠券信息
                $couponPrice = D('coupon')->where('id = '.$orderInfo['coupon_id'])->find();
                if ($orderInfo['price']-$couponPrice['price']>0 && $orderInfo['price']-$couponPrice['price'] < 0.01) {
                    $amount = 0.01;
                }else if($orderInfo['price']-$couponPrice['price'] <0 ){
                    $amount = 0;
                }else{
                    $amount = $orderInfo['price'] - $couponPrice['price'];
                }
                $orderInfo['real_price']        = sprintf("%.2f",$amount); /*$orderInfo['price'] - $couponPrice['price'];*/
                $orderInfo['coupon_name']       = $couponPrice['name'];
                $orderInfo['coupon_price']      = $couponPrice['price'];
            }
            $washLogInfo = D('washLog')->where('ordersn = '.$orderInfo['ordersn'])->order('id desc')->find();
            $this->assign('info',$orderInfo);
            $this->assign('wlinfo',$washLogInfo);
            $this->display('edit_orders');
        }
    }

    /**
     * [refund_list 退款订单列表]
     * @author xiezy
     * @date   2017-10-16
     * @return [type]     [description]
     */
    public function refund_list(){
        $where = null;
        if (IS_POST) {
            switch(I('post.order_find')){
                case 1 :
                    $condition = 'ordersn'; //商户订单号
                    break;
                case 2 :
                    $condition = 'refund_ordersn'; //商户退款单号
                    break;
                case 3 :
                    $condition = 'username'; //用户名
                    break;
                default:
                    break;
            }
            //获取 搜索框 信息
            $query = I('post.keywords',null,'string');

            if($condition=='ordersn'){
                if (trim($query) != null) {
                    $where['r.ordersn'] = array('like','%'.$query.'%');
                }
            }else if($condition=='refund_ordersn'){
                if (trim($query) != null) {
                    $where['r.refund_ordersn'] = array('like','%'.$query.'%');
                }
            }else if($condition=='username'){
                $where['u.user_name'] = array('like','%'.$query.'%');
            }

            switch (I('post.search')) { //查询状态
                case 1:
                    $where['r.refund_status'] = 1; //退款中
                    break;
                case 2:
                    $where['r.refund_status'] = 2; //退款成功
                    break;
                case 99:
                    $where['r.refund_status'] = array('gt','-99'); //全部
                    break;
                default:
                    break;
            }
        }
        if(session(C('USER_AUTH_KEY')) != -1){
            $where['o.server_id'] = session(C('USER_AUTH_KEY'));
        }
        //退款單號不爲空
        $where['refund_ordersn'] = array('NEQ','NULL');
        $where['refund_ordersn'] = array('NEQ','');
        //分页
        $p             = I('get.p',1);
        $refundListNum = $this->refundModel->getRefundCount($where);
        $page          = new \Lib\ORG\Page($refundListNum);
        $limit         = $page->listRows;
        $pageString    = $p.','. $limit;
        $refundList = $this->refundModel->getRefundList($page,$where,$pageString);

        //输出
        if ($refundList) {
            $this->assign('refundList', $refundList );
        }
        $this->assign('page', $page->show());
        $this->display();

    }

    /**
     * [app_refund 申请退款-页面]
     * @author xiezy
     * @date   2017-10-16
     * @return [type]     [description]
     */
    public function app_refund(){
        if (IS_GET) {
            $ordersn = I('get.ordersn');
            $this->assign('ordersn', $ordersn);
        }
        $this->display('app_refund_view');
    }

    /**
     * [refund_audit_view 退款审核详情-页面]
     * @author xiezy
     * @date   2017-10-13
     * @return [type]     [description]
     */
    public function refund_audit_view(){
        if (IS_GET) {
            $where['o.id'] = I('get.id',0,'int');
            if ($where['o.id'] <= 0) {
                //订单ID错误
                $this->redirect(MODULE_NAME.'/'.CONTROLLER_NAME.'/orders_list');
            }

            $orderInfo =  $this->ordersModel->getOrderList($page='',$where,$p=null,$type="find");
            if(isset($orderInfo['coupon_id'])){
                //獲取優惠券信息
                $couponPrice = D('coupon')->where('id = '.$orderInfo['coupon_id'])->find();
                $orderInfo['real_price'] = $orderInfo['price'] - $couponPrice['price']; //实付金额
                $orderInfo['coupon_name'] = $couponPrice['name'];                       //优惠卷名
                $orderInfo['coupon_price'] = $couponPrice['price'];                     //优惠金额
            }
            $washLogInfo = D('washLog')->where('ordersn = '.$orderInfo['ordersn'])->order('id desc')->find();

            $this->assign('info',$orderInfo);
            $this->assign('wlinfo',$washLogInfo);
            $this->display();
        }
    }

    /**
     * [verify_refund 退款审核-操作]
     * @author xiezy
     * @date   2017-10-16
     * @return [type]     [description]
     */
    public function verify_refund(){
        if (IS_POST) {
            $id = I('post.id',0,'int');
            if ($id <= 0) {
                //订单ID错误
                $this->redirect(MODULE_NAME.'/'.CONTROLLER_NAME.'/orders_list');
            }

            $order      = M('order');
            $order_data = $order->find($id); //当前退款订单内容

            $is_refund  = true;//是否可退款
            if ($order_data['card_type'] ==1) {//单次卡
                // 订单表[order]wash_status =1 不给退款
                if ($order_data['wash_status'] >=1) {
                    $is_refund = false;
                }
            }else{//多次卡
                // 洗车表[wash_log] server_id 有值就不能退款
                $washLogInfo = D('washLog')->where('ordersn = '.$order_data['ordersn'])->order('id asc')->find();
                if (!empty($washLogInfo['server_id']) ) {
                    $is_refund = false;
                }
            }

            /*申请退款-审核*/
            if ($is_refund) {
                $order->find($id);
                $order->status = -2;
                if ($order->save()) {
                    $this->ajaxReturn(array('status'=>1,'info'=>'退款審核成功','data'=>$order_data));
                }
            }else{
                $this->ajaxReturn(array('status'=>0,'info'=>'退款審核失敗,請查看清洗已開始或完成!','data'=>$order_data));
            }

        }
    }

    /**
     * [refund_audit 申请退款-操作]
     * @author xiezy
     * @date   2017-10-13
     * @return [type]     [description]
     */
    public function refund_audit(){
        $get_type         = I('post.get_type'); //退款資金來源
        $where['ordersn'] = I('post.ordersn');
        $order            = M('order');
        $order_data       = $order->where($where)->find();
        //判斷是否滿足已审核
        if ( $order_data['status'] >-2 ) {
            //订单号未审核
            $this->ajaxReturn(array('status'=>0,'info'=>'該訂單未審核','data'=>'error'));
        }else if( $order_data['status'] ==-4 ){
            //订单号已退款
            $this->ajaxReturn(array('status'=>0,'info'=>'該訂單已申請退款','data'=>'error'));
        }

        //判断是否使用优惠卷
        if(isset($order_data['coupon_id'])){
            $couponPrice = D('coupon')->where('id = '.$order_data['coupon_id'])->find();//獲取優惠券信息
            $order_data['real_price'] = sprintf("%.2f",$order_data['price'] - $couponPrice['price']); //实付金额
        }else{
            $order_data['real_price'] = sprintf("%.2f",$order_data['price']);
        }

        /*申请退款 同步通知*/
        $ret = static::refundforWx($order_data,$get_type);
        if (!is_array($ret)) {
            $this->ajaxReturn(array('status'=>0,'info'=>$ret));
        }
        if ($ret['return_code'] =='SUCCESS' && $ret['result_code'] =='SUCCESS') {
            // 完善退款订单
            $result = static::add_refund_order($ret,$order_data);
            if($result){
                $this->ajaxReturn(array('status'=>1,'info'=>'申請退款成功','data'=>$ret));
            }
        }else if($ret['return_code'] =='FAIL' || $ret['result_code'] =='FAIL'){
            $reason = (empty($ret['err_code_des']) ? $ret['return_msg'] : $ret['err_code_des']);
            $this->ajaxReturn(array('status'=>0,'info'=>'申請退款失败,原因:'.$reason,'data'=>$ret));
        }
    }

    /**
     * [add_refund_order 添加退款订单信息]
     * @author xiezy
     * @date   2017-10-17
     */
    private static function add_refund_order($ret,$order_data){
        $user           = M('user');
        $userCar        = M('userCar');
        $orderInfo      = M('orderInfo');
        $serverAddress  = M('serverAddress');
        //1.完善原订单表的订单状态
        $order          = M('order');
        $order->find($order_data['id']);  // 查找主键为1的数据
        $order->status  = -4;             // 退款完成
        $result_order   = $order->save(); // 保存当前数据对象

        //2.完善退款表的数据
        $refund                      = M('refund');
        $where['ordersn']            = $ret['out_trade_no'];        //订单号-商户支付
        $save_data['refund_ordersn'] = $ret['out_refund_no'];       //订单号-商户退款
        $save_data['refund_no']      = $ret['refund_id'];           //订单号-微信退款
        $save_data['refund_status']  = 2;                           //退款状态-退款成功
        $save_data['refund_time']    = time();                      //微信退款-金额
        $save_data['refund_price']   = $order_data['real_price'];   //微信退款-金额

        $result_refund = $refund->where($where)->save($save_data);

        if ($result_order && $result_refund) {
            $redundData         = $refund->where($where)->find();
            $userData           = $user->find($redundData['user_id']);
            $serverAddressData  = $serverAddress->find($order_data['server_address_id']);
            $orderInfoData      = $orderInfo->where($where)->find();
            $userCarData        = $userCar->where($userCarWhere)->find($orderInfoData['user_car_id']);
            //完善退款订单信息成功，并发送退款模板
            static::templateSendForRefund($userData,$redundData,$serverAddressData,$userCarData);
            return true;
        }
        return false;
    }

    /**
     * [templateSend 推送模板消息（退款成功）]
     * @author xiezy
     * @date   2017-09-26
     *         用户数据 userData
     *         退款数据 redundData
     *         门店数据 serverData
     *         爱车数据 userCarData
     * @return [type]     [description]
     */
    private static function templateSendForRefund($userData,$redundData,$serverAddressData,$userCarData){
        $userinfo   = $userData;    //微信用户信息
        //推送后模板消息的链接
        // $orderurl   = 'https://washcar.zhfancon.com/Personal/order_list/type/pay_success.html';
        // 模板id
        $templateid = 'VcP4XBkzp9_dfJSawERAabx1KOP-U4VhvxItkhMsNmw'; //退款成功通知

        $pdata=array(
                'first'=>array(
                    'value'=>urlencode("退款成功"),
                    "color"=>"#000000"
                ),
                'keyword1'=>array( //订单编号
                    'value'=>$redundData['ordersn'],
                    'color'=>"#FF0000"
                ),
                'keyword2'=>array( //用户車牌
                    'value'=>$userCarData['license_plate'],
                    'color'=>"#000000"
                ),
                'keyword3'=>array( //退款金额
                    'value'=>$redundData['refund_price'].'元',
                    'color'=>"#000000"
                ),
                'keyword4'=>array( //退款商户或门店
                    'value'=>$serverAddressData['address_name'],
                    'color'=>"#000000"
                ),
                'keyword5'=>array( //退款时间
                    'value'=>date('Y-m-d H:i:s',$redundData['refund_time']),
                    'color'=>"#000000"
                ),
                'remark'=>array(
                    'value'=>"訂單退款完成,如有問題請致電853-65233007或直接在微信公衆號留言,小銘將在第一時間爲您服務!",
                    'color'=>"#FF8800"
                ),
            );
        //推送
        self::pushWXMessage($userinfo, $pdata,$templateid);
    }

    /**
     * [pay_refund 申请退款接口]
     * @author xiezy
     * @date   2017-10-13
     * @param  out_trade_no  商户订单号
     * @param  total_fee     订单金额
     * @param  refund_fee    退款金额
     * @param  refund_no     商户退款单号
     * @return [type]     [description]
     */
    private static function refundforWx($order_data,$type){
        date_default_timezone_set('Asia/Shanghai');

        $wxConfig = require_once __ROOT__ . '/vendor/riverslei/payment-4.0/examples/wxconfig.php';

        $refundNo = time() . rand(1000, 9999); //15位数字

        $refund_account = $type==1? WxConfig::REFUND_UNSETTLED : WxConfig::REFUND_RECHARGE;

        $data = [
            'out_trade_no' => $order_data['ordersn'],  //商户订单号
            'total_fee' => $order_data['real_price'],  //订单金额
            'refund_fee' => $order_data['real_price'], //退款金额
            'refund_no' => $refundNo,            //商户退款单号
            'refund_account' => $refund_account,
            // 'refund_account' => WxConfig::REFUND_UNSETTLED,
            // REFUND_RECHARGE:可用余额退款  REFUND_UNSETTLED:未结算资金退款（默认）
        ];

        try {
            $ret = Refund::run(Config::WX_REFUND, $wxConfig, $data);
        } catch (PayException $e) {
            $ret = $e->errorMessage();
        }
        return $ret;
        // echo json_encode($ret, JSON_UNESCAPED_UNICODE);
    }

    /**
     * [refund_notify 退款通知]
     * @author xiezy
     * @date   2017-09-25
     * @return [type]     [description]
     */
    public function refund_notify(){

    }

    /**
     * [queryforWx 微信查询退款接口]
     * @author xiezy
     * @date   2017-09-26
     * @param  [string]     $ordersn [商户订单号]  四选一
     * @param  [string]     $ordersn [商户退款单号]
     * @param  [string]     $ordersn [微信订单号]
     * @param  [string]     $ordersn [微信退款单号]
     * @return [array]               [查询退款订单结果集]
     */
    private static function queryforWx($ordersn){
        date_default_timezone_set('Asia/Shanghai');

        $wxConfig = require_once __ROOT__ . '/vendor/riverslei/payment-4.0/examples/wxconfig.php';

        //四选一
        $data = [
            'out_trade_no' => $ordersn,   //商户订单号
            // 'refund_no' => '14935506214648',      //商户退款单号
            // 'transaction_id' => '12345678920170430191024123337865', //微信订单号
            // 'refund_id' => '1234567892017043019102412333',          //微信退款单号
        ];

        try {
            $ret = Query::run(Config::WX_REFUND, $wxConfig, $data);
        } catch (PayException $e) {
            echo $e->errorMessage();
            exit;
        }
        return $ret;
    }

    /**
     * 删除订单
     */
    public function delete_orders() {
        $orderId = I('get.id', 0, 'int');
        if ($orderId <= 0) {
            $this->tyAjaxReturn(0, '删除失败');
        }
        $this->ordersModel->where("id=".$orderId)->delete();

        redirect(U(MODULE_NAME.'/'.CONTROLLER_NAME.'/orders_list'));
    }

    /**
     *
     * @param string $orderId
     * @return $orderPrice|null
     */
    private function _getOrderPrice($orderId = null){
        if ($orderId == null) {
            return null;
        }else{
            $where['op.order_id'] = $orderId;
            $orderPrice = $this->OrdersPriceModel->alias('as op')->field('op.*')->where($where)->find();
            if ($orderPrice) {
                return $orderPrice;
            }else{
                return null;
            }
        }
    }

    /**
     * 获取订单用户信息
     * @param 用户ID $memberId
     * @return $email |NULL
     */
    private function _getOrderMember($memberId){
        $where['id'] = $memberId;
        $memberInfo = $this->User->where($where)->getField('email');
        if ($memberInfo) {
            return $memberInfo;
        }else{
            return null;
        }
    }

    /**
     * 获取用户订单地址，返回用户订单地址
     * @param string $addressId 用户订单地址ID
     * @return NULL|unknown
     */
    private function _getOrderAddress($orderId = null){
        if ($orderId == null) {
            return null;
        }
        $where['oa.order_id'] = $orderId;
        $addressInfo = $this->OrdersAddressModel->alias('as oa')->field('oa.*')->
        where($where)->find();
        if ($addressInfo) {
            return $addressInfo;
        }else {
            return null;
        }
    }

    /**
     * 付款记录
     */
//     private function _getPaymentRecords($orderId = null){
//         $where['orders_id'] = $orderId;
//         $paymentRecordsModel = M('PaymentRecords','shop_','DB_CONFIG2');
//         $paymentRecordsInfo = $paymentRecordsModel->where($where)->find();
//         $paymentRecordsInfo['pay_time'] = date('Y-m-d h:i:s', $paymentRecordsInfo['pay_time']);
//         return $paymentRecordsInfo;
//     }

    /**
     * 修改手机号
     */
    public function update_order_info(){
        if(IS_GET){
            $orderId = I('get.order_id',0,'int');
            if ($orderId == 0) {
                $this->error(L('param_error'));
            }

            $data['phone'] = I('get.revisephone','');

            $where['order_id'] = $orderId;

            $OrderAddress = M('orders_address','shop_','DB_CONFIG2');

            $result = $OrderAddress -> where($where) ->save($data);
//             p($OrderAddress->getLastSql());

            if ($result) {
                $this->tyAjaxReturn(1,'成功修改手机号',U(MODULE_NAME.'/'.CONTROLLER_NAME.'/order_details',array('id'=>$orderId)), $result);
            }
            else{
                $this->tyAjaxReturn(0,'手机号未修改，请点击编辑按钮修改！！','');
            }
        }
    }

    /**
     * ajax检测是否付款判断是否能发货
     */
    public function send_status(){
        if(IS_GET){
            $orderId = I('get.order_id',0,'int');
            if ($orderId == 0) {
                $this->error(L('param_error'));
            }
            $checkStatusWhere['id'] = $orderId;
            $checkStatusWhere['pay_status'] = '1';
            $checkOrderStatus = $this->ordersModel->where($checkStatusWhere)->select();
//             p($this->ordersModel->getLastSql());
            if($checkOrderStatus){
                $this->tyAjaxReturn(1,"未付款不能发货！！");
            } else{
                $this->tyAjaxReturn(0,"已付款，请发货！！");
            }
        }
    }

    /**
     * 后台发货填写快递单号
     */
    public function change_delivery(){
        if (IS_POST) {
            $orderId = I('post.order_id',0,'int');
            if ($orderId <= 0) {
                $this->tyAjaxReturn(0,L('找不到order_id'),'');
            }
            $deliveryId = I('post.delivery_id',0,'int');
            if ($deliveryId <= 0) {
                $this->tyAjaxReturn(0,L('请选择快递公司'),'');
            }
            $shippingNo = I('post.logistics_number','','string');
            if ($shippingNo == null) {
                $this->tyAjaxReturn(0,L('找不到shipping_no'),'');
            }
            $shippintTime = I('post.shipping_time', '', 'string');
            if (!$shippintTime) {
                $updateDate['send_time'] = time();
            } else {
                $updateDate['send_time'] = strtotime($shippintTime);
            }
            $where['id'] = $orderId;
            $orderslist = $this->ordersModel->where($where)->find();

            //     		$alipay_config['partner']		= '2088021984225045';
            //     		$alipay_config['key']			= 'q56urs8nlvq8s5qtw16bd9uj49rrwyb7';
            //     		$alipay_config['sign_type']    = strtoupper('MD5');
            //     		$alipay_config['input_charset']= strtolower('utf-8');
            //     		$alipay_config['cacert']    = VENDOR_PATH.'AlipaySendGoods/cacert.pem';
            //     		$alipay_config['transport']    = 'http';
    //TODO:暂时注释支付宝发货接口
//             $alipay_config = return_alipay_config();

//             $deliveryInfo = $this->Delivery->where('id ='.$deliveryId)->find();
//             /**************************请求参数**************************/

//             //支付宝交易号
//             $trade_no = $orderslist['alipay_trade_no'];
//             //必填

//             //物流公司名称
//             $logistics_name = $deliveryInfo['delivery_name'];
//             //必填

//             //物流发货单号

//             $invoice_no = $shippingNo;
//             //物流运输类型
//             $transport_type = 'EXPRESS';
//             //三个值可选：POST（平邮）、EXPRESS（快递）、EMS（EMS）


//             /************************************************************/

//             //构造要请求的参数数组，无需改动
//             $parameter = array(
//                 "service" => "send_goods_confirm_by_platform",
//                 "partner" => trim($alipay_config['partner']),
//                 "trade_no"	=> $trade_no,
//                 "logistics_name"	=> $logistics_name,
//                 "invoice_no"	=> $invoice_no,
//                 "transport_type"	=> $transport_type,
//                 "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
//             );
//             //建立请求
//             $alipaySubmit = new AlipaySubmit($alipay_config);
//             $html_text = $alipaySubmit->buildRequestHttp($parameter);
//             //解析XML
//             //注意：该功能PHP5环境及以上支持，需开通curl、SSL等PHP配置环境。建议本地调试时使用PHP开发软件
//             $doc = new DOMDocument();
//             $doc->loadXML($html_text);
//             //请在这里加上商户的业务逻辑程序代码
            $where['id'] = $orderId;
            $updateDate['logistics_number'] = $shippingNo;
            $updateDate['shipping_status'] = 2;
            $updateDate['status'] = 3;
            $updateDate['delivery_id'] = $deliveryId;
            $result = $this->ordersModel->where($where)->save($updateDate);
//             //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

//             //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
//             //解析XML
//             if( ! empty($doc->getElementsByTagName( "alipay" )->item(0)->nodeValue) ) {
//                 $alipay = $doc->getElementsByTagName( "alipay" )->item(0)->nodeValue;
//                 // echo $alipay;
//                 $this->tyAjaxReturn(1,'发货','',$alipay);
//             } else{
//                 //echo $html_text;
//                 $this->tyAjaxReturn(0,'发货','',$html_text);
//             }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            if ($result) {
                $this->tyAjaxReturn(1,'成功发货！！！',U(MODULE_NAME.'/'.CONTROLLER_NAME.'/order_details',array('id'=>$orderId)));
            }else{
                $this->tyAjaxReturn(0,'发货失败！！！');
            }
        }else{
            $this->tyAjaxReturn(0,L('错误'),'');
        }
    }

    /**
     * 上傳選擇的員工
     */
    public function select_washer(){
        $todayStr = date('Y-m-d', time());
        $todayOP = strtotime($todayStr);

        $where['ordersn'] = $ordersn = I('post.ordersn');
        $data['server_id'] = substr(I('post.staff_id'),0,strlen(I('post.staff_id'))-1); ;//I('post.s_id');
        $data['server_address_id'] = I('post.server_address_id');
        $data['create_time'] = time();
        $newdata['wash_status'] = 1;
        $checkWashLog = $this->washLogModel->where($where)->order('id desc')->find();
        if($checkWashLog){
            $washLogWhere['id'] = $checkWashLog['id'];
            if($checkWashLog['create_time']==''){
                $result = $this->washLogModel->where($washLogWhere)->save($data);
            }
            else if ($checkWashLog['create_time'] !='' && $checkWashLog['create_time'] < $todayOP ){
                $data['ordersn'] = $ordersn;
                $result = $this->washLogModel->add($data);
            }
        }else{
            $data['ordersn'] = $ordersn;
            $result = $this->washLogModel->add($data);
        }


        $orderResult = $this->ordersModel->where($where)->save($newdata);

        if($result !== false && $orderResult !== false){
            $nWhere['o.ordersn'] = $ordersn;
            $checkOrder = $this->ordersModel->alias('as o')->
            join(C('DB_PREFIX').'order_info as oi ON o.ordersn = oi.ordersn')->
            join(C('DB_PREFIX').'user_car as uc ON oi.user_car_id = uc.id')->
            join(C('DB_PREFIX').'user as u ON oi.openid = u.openid')->
            where($nWhere)->order('o.wash_status asc')->find();
            $checkWashLog = $this->washLogModel->where($where)->order('id desc')->find();

            $pdata=array(
                'first'=>array(
                    'value'=>urlencode("您有個新訂單"),
                    "color"=>"#000000"
                ),
                'keyword1'=>array(
                    'value'=>$ordersn,
                    'color'=>"#FF0000"
                ),
                'keyword2'=>array(
                    'value'=>date('Y-m-d H:i',$checkWashLog['create_time']),
                    'color'=>"#000000"
                ),
                'keyword3'=>array(
                    'value'=>urlencode($checkOrder['wash_address']),
                    'color'=>"#000000"
                ),
                'keyword4'=>array(
                    'value'=>urlencode($checkOrder['license_plate'].' '.$checkOrder['color'].' '.$checkOrder['brand']),
                    'color'=>"#000000"
                ),
                'keyword5'=>array(
                    'value'=>urlencode($checkOrder['order_phone']),
                    'color'=>"#000000"
                ),
                'remark'=>array(
                    'value'=>urlencode("請盡快洗車"),
                    'color'=>"#FF8800"
                ),
            );
            $template_id = "CsdqNH202qJftUhZ9Cupxj3RsSe53obCNlKWMiApr38";
            $serverIdList = explode(',', $checkWashLog['server_id']);
            foreach(I('post.s_id') as $s => $v){
                $serverInfo = $this->serverModel->where('id = '.$v)->find();
                $this->pushWXMessage($serverInfo, $pdata ,$template_id);
            }

            $returndata['status'] = 1;
            $returndata['info'] = '選擇成功!';
            $returndata['url'] = U(MODULE_NAME.'/orders/orders_list');
            $this->ajaxReturn($returndata);
        }else{
            $returndata['status'] = 0;
            $returndata['info'] = '選擇失敗!';
            $this->ajaxReturn($returndata);
        }
    }



    /**
     * 执行该方法保存车品牌数据库
     */
//     public function get_car_brand(){
//         $json_arr = '{"returncode":0,"message":"成功","result":{"branditems":[{"id":117,"name":"AC Schnitzer","bfirstletter":"A"},{"id":276,"name":"ALPINA","bfirstletter":"A"},{"id":272,"name":"ARCFOX","bfirstletter":"A"},{"id":34,"name":"阿尔法·罗密欧","bfirstletter":"A"},{"id":35,"name":"阿斯顿·马丁","bfirstletter":"A"},{"id":221,"name":"安凯客车","bfirstletter":"A"},{"id":33,"name":"奥迪","bfirstletter":"A"},{"id":140,"name":"巴博斯","bfirstletter":"B"},{"id":120,"name":"宝骏","bfirstletter":"B"},{"id":15,"name":"宝马","bfirstletter":"B"},{"id":231,"name":"宝沃","bfirstletter":"B"},{"id":40,"name":"保时捷","bfirstletter":"B"},{"id":27,"name":"北京","bfirstletter":"B"},{"id":301,"name":"北汽道达","bfirstletter":"B"},{"id":203,"name":"北汽幻速","bfirstletter":"B"},{"id":173,"name":"北汽绅宝","bfirstletter":"B"},{"id":143,"name":"北汽威旺","bfirstletter":"B"},{"id":208,"name":"北汽新能源","bfirstletter":"B"},{"id":154,"name":"北汽制造","bfirstletter":"B"},{"id":36,"name":"奔驰","bfirstletter":"B"},{"id":95,"name":"奔腾","bfirstletter":"B"},{"id":14,"name":"本田","bfirstletter":"B"},{"id":271,"name":"比速汽车","bfirstletter":"B"},{"id":75,"name":"比亚迪","bfirstletter":"B"},{"id":13,"name":"标致","bfirstletter":"B"},{"id":38,"name":"别克","bfirstletter":"B"},{"id":39,"name":"宾利","bfirstletter":"B"},{"id":37,"name":"布加迪","bfirstletter":"B"},{"id":79,"name":"昌河","bfirstletter":"C"},{"id":76,"name":"长安","bfirstletter":"C"},{"id":299,"name":"长安跨越","bfirstletter":"C"},{"id":163,"name":"长安欧尚","bfirstletter":"C"},{"id":294,"name":"长安轻型车","bfirstletter":"C"},{"id":77,"name":"长城","bfirstletter":"C"},{"id":196,"name":"成功汽车","bfirstletter":"C"},{"id":169,"name":"DS","bfirstletter":"D"},{"id":92,"name":"大发","bfirstletter":"D"},{"id":1,"name":"大众","bfirstletter":"D"},{"id":41,"name":"道奇","bfirstletter":"D"},{"id":32,"name":"东风","bfirstletter":"D"},{"id":187,"name":"东风风度","bfirstletter":"D"},{"id":259,"name":"东风风光","bfirstletter":"D"},{"id":113,"name":"东风风神","bfirstletter":"D"},{"id":165,"name":"东风风行","bfirstletter":"D"},{"id":142,"name":"东风小康","bfirstletter":"D"},{"id":81,"name":"东南","bfirstletter":"D"},{"id":42,"name":"法拉利","bfirstletter":"F"},{"id":11,"name":"菲亚特","bfirstletter":"F"},{"id":3,"name":"丰田","bfirstletter":"F"},{"id":141,"name":"福迪","bfirstletter":"F"},{"id":197,"name":"福汽启腾","bfirstletter":"F"},{"id":8,"name":"福特","bfirstletter":"F"},{"id":96,"name":"福田","bfirstletter":"F"},{"id":282,"name":"福田乘用车","bfirstletter":"F"},{"id":112,"name":"GMC","bfirstletter":"G"},{"id":152,"name":"观致","bfirstletter":"G"},{"id":116,"name":"光冈","bfirstletter":"G"},{"id":82,"name":"广汽传祺","bfirstletter":"G"},{"id":108,"name":"广汽吉奥","bfirstletter":"G"},{"id":24,"name":"哈飞","bfirstletter":"H"},{"id":181,"name":"哈弗","bfirstletter":"H"},{"id":150,"name":"海格","bfirstletter":"H"},{"id":86,"name":"海马","bfirstletter":"H"},{"id":267,"name":"汉腾汽车","bfirstletter":"H"},{"id":43,"name":"悍马","bfirstletter":"H"},{"id":164,"name":"恒天","bfirstletter":"H"},{"id":91,"name":"红旗","bfirstletter":"H"},{"id":245,"name":"华凯","bfirstletter":"H"},{"id":237,"name":"华利","bfirstletter":"H"},{"id":85,"name":"华普","bfirstletter":"H"},{"id":220,"name":"华颂","bfirstletter":"H"},{"id":87,"name":"华泰","bfirstletter":"H"},{"id":260,"name":"华泰新能源","bfirstletter":"H"},{"id":97,"name":"黄海","bfirstletter":"H"},{"id":188,"name":"Icona","bfirstletter":"I"},{"id":46,"name":"Jeep","bfirstletter":"J"},{"id":25,"name":"吉利汽车","bfirstletter":"J"},{"id":84,"name":"江淮","bfirstletter":"J"},{"id":119,"name":"江铃","bfirstletter":"J"},{"id":210,"name":"江铃集团轻汽","bfirstletter":"J"},{"id":270,"name":"江铃集团新能源","bfirstletter":"J"},{"id":44,"name":"捷豹","bfirstletter":"J"},{"id":83,"name":"金杯","bfirstletter":"J"},{"id":145,"name":"金龙","bfirstletter":"J"},{"id":175,"name":"金旅","bfirstletter":"J"},{"id":151,"name":"九龙","bfirstletter":"J"},{"id":109,"name":"KTM","bfirstletter":"K"},{"id":156,"name":"卡尔森","bfirstletter":"K"},{"id":224,"name":"卡升","bfirstletter":"K"},{"id":199,"name":"卡威","bfirstletter":"K"},{"id":101,"name":"开瑞","bfirstletter":"K"},{"id":47,"name":"凯迪拉克","bfirstletter":"K"},{"id":214,"name":"凯翼","bfirstletter":"K"},{"id":219,"name":"康迪全球鹰","bfirstletter":"K"},{"id":100,"name":"科尼赛克","bfirstletter":"K"},{"id":9,"name":"克莱斯勒","bfirstletter":"K"},{"id":241,"name":"LOCAL MOTORS","bfirstletter":"L"},{"id":118,"name":"Lorinser","bfirstletter":"L"},{"id":48,"name":"兰博基尼","bfirstletter":"L"},{"id":54,"name":"劳斯莱斯","bfirstletter":"L"},{"id":52,"name":"雷克萨斯","bfirstletter":"L"},{"id":10,"name":"雷诺","bfirstletter":"L"},{"id":124,"name":"理念","bfirstletter":"L"},{"id":80,"name":"力帆汽车","bfirstletter":"L"},{"id":89,"name":"莲花汽车","bfirstletter":"L"},{"id":78,"name":"猎豹汽车","bfirstletter":"L"},{"id":51,"name":"林肯","bfirstletter":"L"},{"id":53,"name":"铃木","bfirstletter":"L"},{"id":279,"name":"领克","bfirstletter":"L"},{"id":204,"name":"陆地方舟","bfirstletter":"L"},{"id":88,"name":"陆风","bfirstletter":"L"},{"id":49,"name":"路虎","bfirstletter":"L"},{"id":50,"name":"路特斯","bfirstletter":"L"},{"id":56,"name":"MINI","bfirstletter":"M"},{"id":58,"name":"马自达","bfirstletter":"M"},{"id":57,"name":"玛莎拉蒂","bfirstletter":"M"},{"id":55,"name":"迈巴赫","bfirstletter":"M"},{"id":129,"name":"迈凯伦","bfirstletter":"M"},{"id":20,"name":"名爵","bfirstletter":"M"},{"id":168,"name":"摩根","bfirstletter":"M"},{"id":130,"name":"纳智捷","bfirstletter":"N"},{"id":213,"name":"南京金龙","bfirstletter":"N"},{"id":60,"name":"讴歌","bfirstletter":"O"},{"id":59,"name":"欧宝","bfirstletter":"O"},{"id":146,"name":"欧朗","bfirstletter":"O"},{"id":61,"name":"帕加尼","bfirstletter":"P"},{"id":26,"name":"奇瑞","bfirstletter":"Q"},{"id":122,"name":"启辰","bfirstletter":"Q"},{"id":62,"name":"起亚","bfirstletter":"Q"},{"id":235,"name":"前途","bfirstletter":"Q"},{"id":63,"name":"日产","bfirstletter":"R"},{"id":19,"name":"荣威","bfirstletter":"R"},{"id":174,"name":"如虎","bfirstletter":"R"},{"id":296,"name":"瑞驰新能源","bfirstletter":"R"},{"id":103,"name":"瑞麒","bfirstletter":"R"},{"id":45,"name":"smart","bfirstletter":"S"},{"id":269,"name":"SWM斯威汽车","bfirstletter":"S"},{"id":64,"name":"萨博","bfirstletter":"S"},{"id":205,"name":"赛麟","bfirstletter":"S"},{"id":68,"name":"三菱","bfirstletter":"S"},{"id":149,"name":"陕汽通家","bfirstletter":"S"},{"id":155,"name":"上汽大通","bfirstletter":"S"},{"id":66,"name":"世爵","bfirstletter":"S"},{"id":90,"name":"双环","bfirstletter":"S"},{"id":69,"name":"双龙","bfirstletter":"S"},{"id":162,"name":"思铭","bfirstletter":"S"},{"id":65,"name":"斯巴鲁","bfirstletter":"S"},{"id":238,"name":"斯达泰克","bfirstletter":"S"},{"id":67,"name":"斯柯达","bfirstletter":"S"},{"id":202,"name":"泰卡特","bfirstletter":"T"},{"id":133,"name":"特斯拉","bfirstletter":"T"},{"id":161,"name":"腾势","bfirstletter":"T"},{"id":283,"name":"WEY","bfirstletter":"W"},{"id":102,"name":"威麟","bfirstletter":"W"},{"id":99,"name":"威兹曼","bfirstletter":"W"},{"id":192,"name":"潍柴英致","bfirstletter":"W"},{"id":284,"name":"蔚来","bfirstletter":"W"},{"id":70,"name":"沃尔沃","bfirstletter":"W"},{"id":114,"name":"五菱汽车","bfirstletter":"W"},{"id":167,"name":"五十铃","bfirstletter":"W"},{"id":98,"name":"西雅特","bfirstletter":"X"},{"id":12,"name":"现代","bfirstletter":"X"},{"id":185,"name":"新凯","bfirstletter":"X"},{"id":306,"name":"鑫源","bfirstletter":"X"},{"id":71,"name":"雪佛兰","bfirstletter":"X"},{"id":72,"name":"雪铁龙","bfirstletter":"X"},{"id":111,"name":"野马汽车","bfirstletter":"Y"},{"id":110,"name":"一汽","bfirstletter":"Y"},{"id":144,"name":"依维柯","bfirstletter":"Y"},{"id":73,"name":"英菲尼迪","bfirstletter":"Y"},{"id":93,"name":"永源","bfirstletter":"Y"},{"id":298,"name":"宇通客车","bfirstletter":"Y"},{"id":263,"name":"驭胜","bfirstletter":"Y"},{"id":232,"name":"御捷","bfirstletter":"Y"},{"id":307,"name":"裕路","bfirstletter":"Y"},{"id":286,"name":"云度","bfirstletter":"Y"},{"id":182,"name":"之诺","bfirstletter":"Z"},{"id":206,"name":"知豆","bfirstletter":"Z"},{"id":22,"name":"中华","bfirstletter":"Z"},{"id":74,"name":"中兴","bfirstletter":"Z"},{"id":94,"name":"众泰","bfirstletter":"Z"}]}}';

//         $json_arr = json_decode($json_arr,true);

//         $insertArr = $json_arr['result']['branditems'];
//         $brandModel = D('carBrand');
//         foreach($insertArr as$key => $val){
//             $data['id'] = $val['id'];
//             $data['brand'] = $val['name'];
//             $data['letter'] = $val['bfirstletter'];
//             $result = $brandModel->add($data);
//             unset($data);
//         }

//         p($result);
//     }
}

?>
